<?php
namespace QuestionPlus\Service\QuestionPlus\Impl;

use QuestionPlus\Service\QuestionPlus\QuestionPlumberService;
use Topxia\Service\Common\BaseService;

use QuestionPlus\Service\Import\Import;

use QuestionPlus\Service\Export\QuestionExport\DocMaker;

class QuestionPlumberServiceImpl extends BaseService implements QuestionPlumberService
{
    public function questionImport ($target, $importType, $path)
    {
        $questionImport = new Import($target, $importType);
        $questions = $questionImport->getQuestions($path);

        return $questions;
    }

    public function verifyCount ($questions, $count)
    {
        $questionCounts = array_map(function($type){
            return count($type);
        }, $questions);

        return array_sum($questionCounts) == $count;
    }

    public function createQuestions($questions)
    {
        $count = 0;
        $connection = $this->getKernel()->getConnection();
        $connection->beginTransaction();

        try {
            foreach ($questions as $type => $typeQuestins) {
                if ($type == 'material') {
                    $count += $this->batchProcessMaterialQuestions($typeQuestins);
                } else {
                    $count += $this->batchProcessNotMaterialQuestions($typeQuestins);
                }
            }
            $connection->commit();
        } catch (\Exception $e) {
            $connection->rollback();
            $count = 0;
            throw $e;
        }

        return $count;
    }

    private function batchProcessMaterialQuestions($materialQuestions)
    {
        $count = 0 ;
        foreach ($materialQuestions as $materialQuestion) {
            $questions = $materialQuestion['questions'];
            unset($materialQuestion['questions']);
            $materialQuestion;
            $materialQuestion = $this->createQuestion($materialQuestion);
            $this->batchProcessNotMaterialQuestions($questions, $materialQuestion['id']);
            $count++;
        }
        return $count;
    }

    private function batchProcessNotMaterialQuestions($questions, $parentId = null)
    {
        $count = 0;
        foreach ($questions as $question) {
            if ($parentId) {
                $question['parentId'] = $parentId;
            }
            $this->createQuestion($question);
            $count++;
        }
        return $count;
    }

    private function createQuestion($question)
    {
        return $this->getQuestionService()->createQuestion($question);
    }

    public function getQuestionFilePath ($file, $course)
    {
        $filenamePrefix = "questions_import_course_{$course['id']}_";
        $hash = substr(md5($filenamePrefix . time()), -8);
        $ext = $file->getClientOriginalExtension();

        if (empty($ext)) {
            $filename = $filenamePrefix . $hash;
        } else {
            $filename = $filenamePrefix . $hash . '.' . $ext;
        }

        $directory = $this->getKernel()->getParameter('topxia.upload.public_directory') . '/tmp';
        $file = $file->move($directory, $filename);          

        $path = $directory . '/'. $filename;

        return realpath($path);
    }

    public function cleanQuestionFile($path)
    {
        @unlink($path);
    }

    public function htmlToWord ($content)
    {
        $content = preg_replace('#<a\s*.*?\s*>#i' , '' , $content);
        $content = preg_replace('#<\/a>#i' , '' , $content);
        $content = preg_replace('#font-size:\s*(.*?);#i' , '' , $content);

        $images = array();
        $files = array();

        if (preg_match_all('#<img\ssrc=[\"\'](.*?)[\"\']\s?/>#i',$content ,$matches)) {

            $imagePaths = $matches[1];
            foreach ($imagePaths as $imagePath) {
                $imagePath = trim($imagePath);
                if ($imagePath) {
                    $files[] = $imagePath;

                    $imagePath = explode('?', $imagePath);
                    $imagePath = $imagePath[0];

                    $directory = $this->getKernel()->getParameter('topxia.upload.public_directory');
                    $directory = substr($directory, 0, -6) . $imagePath;

                    $images[] = realpath($directory);
                }
            }
        }

        $doc = new DocMaker();

        $doc->AddContents("question.html", $doc->GetMimeType("question.html"), $content);
        
        foreach ($images as $key => $image) {
            if (@fopen($image , 'r')) {
                $img = @file_get_contents($image);
                if ($content) {
                    $doc->AddContents($files[$key], $doc->GetMimeType($image), $img);
                }
            }
        }

        return $doc->GetFile();
    }

    private function getQuestionService()
    {
        return $this->createService('Question.QuestionService');
    }
}